﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Http;

using Game.Utilities.Log;
using Web.Server.App_Start;

namespace Web.Server
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

           


            SignalRConfig.Register();
            
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            NLogManager.LogMessage("\r\n --- START SERVER ---\r\n");

            
           
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (this.Context.Request.Path.Contains("signalr/negotiate"))
            {
                if (!string.IsNullOrEmpty(this.Context.Request.Headers["Origin"]))
                {
                    this.Context.Request.Headers.Remove("Origin");
                }

                this.Context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                this.Context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                this.Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                this.Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var ex = Server.GetLastError().GetBaseException();
            var url = HttpContext.Current.Request.Url.AbsoluteUri.ToLower();

            var webex = ex as HttpException;
            if (webex != null)
            {
                if (webex.ErrorCode == -2147467259)
                {
                    return;
                }
                NLogManager.LogMessage(string.Format("\r\nError Code\t: {0}", webex.ErrorCode.ToString()));
            }
            NLogManager.LogMessage(string.Format("{0}{1}{2}{3}", ex.Message, Environment.NewLine, ex.StackTrace, url));
        }

        protected void Application_End(object sender, EventArgs e)
        {
            NLogManager.LogMessage("\r\n --- SHUTDOWN SERVER ---\r\n");
        }


    }
}